package com.olecloud.www.ui

import android.Manifest
import android.content.*
import android.net.Uri
import android.net.VpnService
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import com.tbruyelle.rxpermissions.RxPermissions
import com.olecloud.www.R
import kotlinx.android.synthetic.main.activity_main.*
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import com.olecloud.www.AppConfig
import org.jetbrains.anko.*
import java.lang.ref.SoftReference
import java.net.URL
import android.content.IntentFilter
import android.graphics.Bitmap
import android.opengl.Visibility
import android.os.Build
import android.os.Handler
import android.os.Message
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AlertDialog
import android.support.v7.widget.helper.ItemTouchHelper
import android.telecom.Call
import android.util.Log
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.google.gson.Gson
import com.olecloud.www.dto.AdImageInfo
import com.olecloud.www.dto.AngConfig
import com.olecloud.www.dto.NetworkAppInfo
import com.olecloud.www.dto.VmessQRCode
import com.olecloud.www.extension.defaultDPreference
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import java.util.concurrent.TimeUnit
import com.olecloud.www.helper.SimpleItemTouchHelperCallback
import com.olecloud.www.util.*
import com.olecloud.www.util.AngConfigManager.configs
import com.zhy.http.okhttp.OkHttpUtils
import kotlinx.android.synthetic.main.activity_main.recycler_view
import java.io.IOException
import java.util.ArrayList
import java.util.regex.Pattern
import com.zhy.http.okhttp.callback.StringCallback as StringCallback1

class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedListener {
    companion object {
        private const val REQUEST_CODE_VPN_PREPARE = 0
        private const val REQUEST_SCAN = 1
        private const val REQUEST_FILE_CHOOSER = 2
        private const val REQUEST_SCAN_URL = 3
    }
    private var baseUrl: String = ""
    var handler:  Handler = object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when(msg?.what) {
                99999 -> {
                    OkHttpUtils.get().url("https://jiayi2020.github.io/base_url/get_url/").build().execute(object : StringCallback1() {
                        override fun onError(call: okhttp3.Call?, e: java.lang.Exception?, id: Int) {
                            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                        }

                        override fun onResponse(response: String?, id: Int) {
                            Log.i("legendqi", response)
                            val pattern = "<span>.+?</span>"
                            val matcher = Pattern.compile(pattern)
                            val result = matcher.matcher(response)
                            result.find()
                            baseUrl = result.group().replace("<span>", "").replace("</span>", "")
                            main_webview.loadUrl(baseUrl + "/vpnapp/splash")
                            OkHttpUtils.get().url(baseUrl + "/api/ads").build().execute(object : StringCallback1() {
                                override fun onError(call: okhttp3.Call?, e: java.lang.Exception?, id: Int) {
                                    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                                }

                                override fun onResponse(response: String?, id: Int) {
                                    Log.i("legendqi", response)
                                    val imageBean = Gson().fromJson(response, AdImageInfo::class.java)
                                    Glide.with(this@MainActivity).load(imageBean.data[0].img).into(ad_image)
                                    ad_image.setOnClickListener(object: View.OnClickListener {
                                        override fun onClick(v: View?) {
                                            val intent = Intent(Intent.ACTION_VIEW)
                                            intent.addCategory(Intent.CATEGORY_BROWSABLE)
                                            intent.data = Uri.parse(imageBean.data[0].url)
                                            startActivity(intent)
                                            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                                        }
                                    })
                                    Toast.makeText(this@MainActivity, "正在初始化环境", Toast.LENGTH_LONG).show()
                                }

                            })
                        }
                    })
                }
            }
        }
    }

//    private var url: String = "http://192.168.3.2/home"
    var isRunning = false
        set(value) {
            field = value
            adapter.changeable = !value
            if (value) {
                fab.imageResource = R.drawable.ic_v
                tv_test_state.text = getString(R.string.connection_connected)
            } else {
                fab.imageResource = R.drawable.ic_v_idle
                tv_test_state.text = getString(R.string.connection_not_connected)
            }
            hideCircle()
        }

    private val adapter by lazy { MainRecyclerAdapter(this) }
    private var mItemTouchHelper: ItemTouchHelper? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val settings = main_webview.settings
        settings.javaScriptEnabled = true
        // Enable and setup web view cache
        settings.setAppCacheEnabled(true)
        settings.cacheMode = WebSettings.LOAD_DEFAULT
        settings.setAppCacheEnabled(true)
        settings.setAppCachePath(cacheDir.path)
        settings.setSupportZoom(false)
        // Enable zooming in web view
        settings.builtInZoomControls = false
        settings.displayZoomControls = false
        // Enable disable images in web view
        settings.blockNetworkImage = false
        // Whether the WebView should load image resources
        settings.loadsImagesAutomatically = true

        // More web view settings
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            settings.safeBrowsingEnabled = true
        }
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.javaScriptCanOpenWindowsAutomatically = true
        // More optional settings, you can enable it by yourself
        settings.domStorageEnabled = true
        settings.setSupportMultipleWindows(true)
        settings.loadWithOverviewMode = true
        settings.setGeolocationEnabled(true)
        settings.allowFileAccess = true
        //webview setting
//        main_webview.fitsSystemWindows = true
        /* if SDK version is greater of 19 then activate hardware acceleration
        otherwise activate software acceleration  */
        main_webview.setLayerType(View.LAYER_TYPE_HARDWARE,null)
        if (!isNetworkOnline()) {
            showNetWorkDialog()
        } else {
            handler.sendEmptyMessageDelayed(99999, 3000)
        }
//        val testData = JSONObject("{add: \"\", aid: 2, class: 0, host: \"dd.com\", id: \"3c818c30-e456-3cb1-9bef-b1a3f5d332e8\", index: 4, net: \"ws\", path: \"\", port: 443, ps: \"\", tls: \"tls\", type: \"\", v: 2}")
//        Log.i("legend", "changedata: " + testData.get("host"))
        // Set web view client
        main_webview.webViewClient = object  : WebViewClient(){
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                Log.i("legendqi", "onPageStarted")
                // 开始加载网页，然后显示图片或者广告图片
                // Page loading started
                // Do something
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                ad_image.visibility=View.GONE
                main_webview.visibility=View.VISIBLE
                // 显示网页
                Log.i("legendqi", "onPageFinished")
            }
        }
        main_webview!!.addJavascriptInterface(this,"VPNService")
        title = getString(R.string.title_server)
        setSupportActionBar(toolbar)

        fab.setOnClickListener {
            if (isRunning) {
                Utils.stopVService(this)
            } else {
                val intent = VpnService.prepare(this)
                if (intent == null) {
                    startV2Ray()
                } else {
                    startActivityForResult(intent, REQUEST_CODE_VPN_PREPARE)
                }
            }
        }
        layout_test.setOnClickListener {
            if (isRunning) {
                val socksPort = 10808//Utils.parseInt(defaultDPreference.getPrefString(SettingsActivity.PREF_SOCKS_PORT, "10808"))

                tv_test_state.text = getString(R.string.connection_test_testing)
                doAsync {
                    val result = Utils.testConnection(this@MainActivity, socksPort)
                    uiThread {
                        tv_test_state.text = Utils.getEditable(result)
                    }
                }
            } else {
//                tv_test_state.text = getString(R.string.connection_test_fail)
            }
        }

        recycler_view.setHasFixedSize(true)
        recycler_view.layoutManager = LinearLayoutManager(this)
        recycler_view.adapter = adapter

        val callback = SimpleItemTouchHelperCallback(adapter)
        mItemTouchHelper = ItemTouchHelper(callback)
        mItemTouchHelper?.attachToRecyclerView(recycler_view)


        val toggle = ActionBarDrawerToggle(
                this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
        drawer_layout.addDrawerListener(toggle)
        drawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
        toggle.syncState()
        nav_view.setNavigationItemSelectedListener(this)
    }

    fun showNetWorkDialog() {
        AlertDialog.Builder(this)
                .setTitle("警告")
                .setMessage("您的网络不可用,请检查!")
                .setPositiveButton("确定") { dialog, which -> dialog.dismiss() }.show()
    }

    fun isNetworkOnline(): Boolean {
        val runtime = Runtime.getRuntime()
        try {
            val ipProcess = runtime.exec("ping -c 1 -w 1 www.baidu.com")
            val exitValue = ipProcess.waitFor()
            Log.i("Avalible", "Process:$exitValue")
            return exitValue == 0
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }

        return false
    }

    @JavascriptInterface
    fun getAppProxySetting(): Boolean {
        // 获取分应用代理开关状态
        return defaultDPreference.getPrefBoolean(SettingsActivity.PREF_PER_APP_PROXY, false)
    }

    @JavascriptInterface
    fun getAppInfo(): String {
        val appInfos = ArrayList<NetworkAppInfo>()
        val blacklist = defaultDPreference.getPrefStringSet(PerAppProxyActivity.PREF_PER_APP_PROXY_SET, null)
        val apps = AppManagerUtil.loadNetworkAppList(this)

        apps.forEach { one ->
            if (blacklist !== null) {
                if ((blacklist.contains(one.packageName))) {
                    one.isSelected = 1
                } else {
                    one.isSelected = 0
                }
            } else {
                one.isSelected = 0
            }
            appInfos.add(NetworkAppInfo(one.appName, one.packageName, one.isSelected))
        }
        return Gson().toJson(appInfos)
    }

    @JavascriptInterface
    fun getRouterModel(): String {
        return applicationContext.defaultDPreference.getPrefString(SettingsActivity.PREF_ROUTING_MODE, "0")
    }

    @JavascriptInterface
    fun setRouterModel(model: String) {
        applicationContext.defaultDPreference.setPrefString(SettingsActivity.PREF_ROUTING_MODE, model)
    }

    @JavascriptInterface
    fun setAppProxy(packages: String){
        val packs = HashSet<String>()
        packages.split("==").forEach { item ->
            packs.add(item)
        }
        defaultDPreference.setPrefStringSet(PerAppProxyActivity.PREF_PER_APP_PROXY_SET, packs)
    }

    @JavascriptInterface
    fun appProxySetting(isStarted: String) {
        var proxyStatus = false
        if (isStarted.equals("true")) {
            proxyStatus = true
        }
        // 设置分应用代理开关
        defaultDPreference.setPrefBoolean(SettingsActivity.PREF_PER_APP_PROXY, proxyStatus)
    }

    @JavascriptInterface
    fun startVPNService(vmess: String) : Boolean  {
        Log.i("legendqi", "调用开启vpn" + vmess)
//        Toast.makeText(this@MainActivity, "vpn延迟" + tcpVmess(vmess), Toast.LENGTH_LONG).show()
//        Log.i("legendqi", "vpn延迟" + tcpVmess(vmess))
        AngConfigManager.configs.vmess.clear()
        AngConfigManager.importConfig(vmess, "")
        AngConfigManager.setActiveServer(0)
        val intent = VpnService.prepare(this)
        if (intent == null) {
            isRunning = true
            return startV2Ray()
        } else {
            startActivityForResult(intent, REQUEST_CODE_VPN_PREPARE)
            isRunning = true
            return true
        }
    }

    @JavascriptInterface
    fun stopVPNService() : Boolean  {
        Utils.stopVService(this)
        Log.i("legendqi", "停止vpn")
        return true
    }

    @JavascriptInterface
    fun chargeByMobile(chargeUrl: String?) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addCategory(Intent.CATEGORY_BROWSABLE)
        intent.data = Uri.parse(chargeUrl)
        startActivity(intent)
    }

    fun startVPN(vmessString: String) {
        AngConfigManager.configs.vmess.clear()
        AngConfigManager.importConfig(vmessString, "")
        AngConfigManager.setActiveServer(0)
        val intent = VpnService.prepare(this)
        if (intent == null) {
            startV2Ray()
        } else {
            startActivityForResult(intent, REQUEST_CODE_VPN_PREPARE)
        }
    }

    @JavascriptInterface
    fun tcpVmess(vmess: String): String {
        try {
            var result = vmess.replace(AppConfig.VMESS_PROTOCOL, "")
            result = Utils.decode(result)
            if (TextUtils.isEmpty(result)) {
                Log.i("legendqi", "restult is null")
                return "-1ms"
            }
            val vmessQRCode = Gson().fromJson(result, VmessQRCode::class.java)
            return Utils.tcping(vmessQRCode.add, Utils.parseInt(vmessQRCode.port))
        } catch (e: Exception) {
            Log.i("legendqi", e.toString())
            Log.i("legendqi", "restult is exception")
            return "-1ms"
        }

    }

    fun startV2Ray() : Boolean {
        if (AngConfigManager.configs.index < 0) {
            return false
        }
        return Utils.startVService(this)
    }

    override fun onStart() {
        super.onStart()
        isRunning = false

//        val intent = Intent(this.applicationContext, V2RayVpnService::class.java)
//        intent.`package` = AppConfig.ANG_PACKAGE
//        bindService(intent, mConnection, BIND_AUTO_CREATE)

        mMsgReceive = ReceiveMessageHandler(this@MainActivity)
        registerReceiver(mMsgReceive, IntentFilter(AppConfig.BROADCAST_ACTION_ACTIVITY))
        MessageUtil.sendMsg2Service(this, AppConfig.MSG_REGISTER_CLIENT, "")
    }

    override fun onStop() {
        super.onStop()
        if (mMsgReceive != null) {
            unregisterReceiver(mMsgReceive)
            mMsgReceive = null
        }
    }

    public override fun onResume() {
        super.onResume()
        adapter.updateConfigList()
    }

    public override fun onPause() {
        super.onPause()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_CODE_VPN_PREPARE ->
                if (resultCode == RESULT_OK) {
                    startV2Ray()
                }
            REQUEST_SCAN ->
                if (resultCode == RESULT_OK) {
                    importBatchConfig(data?.getStringExtra("SCAN_RESULT"))
                }
            REQUEST_FILE_CHOOSER -> {
                if (resultCode == RESULT_OK) {
                    val uri = data!!.data
                    readContentFromUri(uri)
                }
            }
            REQUEST_SCAN_URL ->
                if (resultCode == RESULT_OK) {
                    importConfigCustomUrl(data?.getStringExtra("SCAN_RESULT"))
                }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
        R.id.import_qrcode -> {
            importQRcode(REQUEST_SCAN)
            true
        }
        R.id.import_clipboard -> {
            importClipboard()
            true
        }
        R.id.import_manually_vmess -> {
            startActivity<ServerActivity>("position" to -1, "isRunning" to isRunning)
            adapter.updateConfigList()
            true
        }
        R.id.import_manually_ss -> {
            startActivity<Server3Activity>("position" to -1, "isRunning" to isRunning)
            adapter.updateConfigList()
            true
        }
        R.id.import_manually_socks -> {
            startActivity<Server4Activity>("position" to -1, "isRunning" to isRunning)
            adapter.updateConfigList()
            true
        }
        R.id.import_config_custom_clipboard -> {
            importConfigCustomClipboard()
            true
        }
        R.id.import_config_custom_local -> {
            importConfigCustomLocal()
            true
        }
        R.id.import_config_custom_url -> {
            importConfigCustomUrlClipboard()
            true
        }
        R.id.import_config_custom_url_scan -> {
            importQRcode(REQUEST_SCAN_URL)
            true
        }

//        R.id.sub_setting -> {
//            startActivity<SubSettingActivity>()
//            true
//        }

        R.id.sub_update -> {
            importConfigViaSub()
            true
        }

        R.id.export_all -> {
            if (AngConfigManager.shareAll2Clipboard() == 0) {
                //remove toast, otherwise it will block previous warning message
            } else {
                toast(R.string.toast_failure)
            }
            true
        }

        R.id.ping_all -> {
            for (k in 0 until configs.vmess.count()) {
                configs.vmess[k].testResult = ""
                adapter.updateConfigList()
            }
            for (k in 0 until configs.vmess.count()) {
                if (configs.vmess[k].configType != AppConfig.EConfigType.Custom) {
                    doAsync {
                        configs.vmess[k].testResult = Utils.tcping(configs.vmess[k].address, configs.vmess[k].port)
                        uiThread {
                            adapter.updateSelectedItem(k)
                        }
                    }
                }
            }
            true
        }

//        R.id.settings -> {
//            startActivity<SettingsActivity>("isRunning" to isRunning)
//            true
//        }
//        R.id.logcat -> {
//            startActivity<LogcatActivity>()
//            true
//        }
        else -> super.onOptionsItemSelected(item)
    }


    /**
     * import config from qrcode
     */
    fun importQRcode(requestCode: Int): Boolean {
//        try {
//            startActivityForResult(Intent("com.google.zxing.client.android.SCAN")
//                    .addCategory(Intent.CATEGORY_DEFAULT)
//                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP), requestCode)
//        } catch (e: Exception) {
        RxPermissions(this)
                .request(Manifest.permission.CAMERA)
                .subscribe {
                    if (it)
                        startActivityForResult<ScannerActivity>(requestCode)
                    else
                        toast(R.string.toast_permission_denied)
                }
//        }
        return true
    }

    /**
     * import config from clipboard
     */
    fun importClipboard()
            : Boolean {
        try {
            val clipboard = Utils.getClipboard(this)
            importBatchConfig(clipboard)
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
        return true
    }

    fun importBatchConfig(server: String?, subid: String = "") {
        val count = AngConfigManager.importBatchConfig(server, subid)
        if (count > 0) {
            toast(R.string.toast_success)
            adapter.updateConfigList()
        } else {
            toast(R.string.toast_failure)
        }
    }

    fun importConfigCustomClipboard()
            : Boolean {
        try {
            val configText = Utils.getClipboard(this)
            if (TextUtils.isEmpty(configText)) {
                toast(R.string.toast_none_data_clipboard)
                return false
            }
            importCustomizeConfig(configText)
            return true
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }

    /**
     * import config from local config file
     */
    fun importConfigCustomLocal(): Boolean {
        try {
            showFileChooser()
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
        return true
    }

    fun importConfigCustomUrlClipboard()
            : Boolean {
        try {
            val url = Utils.getClipboard(this)
            if (TextUtils.isEmpty(url)) {
                toast(R.string.toast_none_data_clipboard)
                return false
            }
            return importConfigCustomUrl(url)
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }

    /**
     * import config from url
     */
    fun importConfigCustomUrl(url: String?): Boolean {
        try {
            if (!Utils.isValidUrl(url)) {
                toast(R.string.toast_invalid_url)
                return false
            }
            doAsync {
                val configText = URL(url).readText()
                uiThread {
                    importCustomizeConfig(configText)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
        return true
    }

    /**
     * import config from sub
     */
    fun importConfigViaSub()
            : Boolean {
        try {
            toast(R.string.title_sub_update)
            val subItem = AngConfigManager.configs.subItem
            for (k in 0 until subItem.count()) {
                if (TextUtils.isEmpty(subItem[k].id)
                        || TextUtils.isEmpty(subItem[k].remarks)
                        || TextUtils.isEmpty(subItem[k].url)
                ) {
                    continue
                }
                val id = subItem[k].id
                val url = subItem[k].url
                if (!Utils.isValidUrl(url)) {
                    continue
                }
                Log.d("Main", url)
                doAsync {
                    val configText = URL(url).readText()
                    uiThread {
                        importBatchConfig(Utils.decode(configText), id)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
        return true
    }

    /**
     * show file chooser
     */
    private fun showFileChooser() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "*/*"
        intent.addCategory(Intent.CATEGORY_OPENABLE)

        try {
            startActivityForResult(
                    Intent.createChooser(intent, getString(R.string.title_file_chooser)),
                    REQUEST_FILE_CHOOSER)
        } catch (ex: android.content.ActivityNotFoundException) {
            toast(R.string.toast_require_file_manager)
        }
    }

    /**
     * read content from uri
     */
    private fun readContentFromUri(uri: Uri) {
        RxPermissions(this)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe {
                    if (it) {
                        try {
                            val inputStream = contentResolver.openInputStream(uri)
                            val configText = inputStream.bufferedReader().readText()
                            importCustomizeConfig(configText)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    } else
                        toast(R.string.toast_permission_denied)
                }
    }

    /**
     * import customize config
     */
    fun importCustomizeConfig(server: String?) {
        if (server == null) {
            return
        }
        if (!V2rayConfigUtil.isValidConfig(server)) {
            toast(R.string.toast_config_file_invalid)
            return
        }
        val resId = AngConfigManager.importCustomizeConfig(server)
        if (resId > 0) {
            toast(resId)
        } else {
            toast(R.string.toast_success)
            adapter.updateConfigList()
        }
    }

//    val mConnection = object : ServiceConnection {
//        override fun onServiceDisconnected(name: ComponentName?) {
//        }
//
//        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
//            sendMsg(AppConfig.MSG_REGISTER_CLIENT, "")
//        }
//    }

    private
    var mMsgReceive: BroadcastReceiver? = null

    private class ReceiveMessageHandler(activity: MainActivity) : BroadcastReceiver() {
        internal var mReference: SoftReference<MainActivity> = SoftReference(activity)
        override fun onReceive(ctx: Context?, intent: Intent?) {
            val activity = mReference.get()
            when (intent?.getIntExtra("key", 0)) {
                AppConfig.MSG_STATE_RUNNING -> {
                    activity?.isRunning = true
                }
                AppConfig.MSG_STATE_NOT_RUNNING -> {
                    activity?.isRunning = false
                }
                AppConfig.MSG_STATE_START_SUCCESS -> {
                    activity?.toast(R.string.toast_services_success)
                    activity?.isRunning = true
                }
                AppConfig.MSG_STATE_START_FAILURE -> {
                    activity?.toast(R.string.toast_services_failure)
                    activity?.isRunning = false
                }
                AppConfig.MSG_STATE_STOP_SUCCESS -> {
                    activity?.isRunning = false
                }
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false)
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    fun showCircle() {
        fabProgressCircle?.show()
    }

    fun hideCircle() {
        try {
            Observable.timer(300, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        if (fabProgressCircle.isShown) {
                            fabProgressCircle.hide()
                        }
                    }
        } catch (e: Exception) {
        }
    }

    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        when (item.itemId) {
            //R.id.server_profile -> activityClass = MainActivity::class.java
            R.id.sub_setting -> {
                startActivity<SubSettingActivity>()
            }
            R.id.settings -> {
                startActivity<SettingsActivity>("isRunning" to isRunning)
            }
            R.id.feedback -> {
                Utils.openUri(this, AppConfig.v2rayNGIssues)
            }
            R.id.promotion -> {
                Utils.openUri(this, AppConfig.promotionUrl)
            }
            R.id.donate -> {
//                startActivity<InappBuyActivity>()
            }
            R.id.logcat -> {
                startActivity<LogcatActivity>()
            }
        }
        drawer_layout.closeDrawer(GravityCompat.START)
        return true
    }
}